package hsb.learn;

import org.apache.commons.imaging.Imaging;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.Base64;


public class Main {
    static {
        //  System.loadLibrary("awt");
    }

    public static void main(String[] args) throws IOException {

        String base64Imag = "";

        byte[] imageBytes = base64Img2ByteArray(base64Imag);
        // Files.write(Path.of("2.png"), imageBytes);
        BufferedImage bufferedImage = saveByteArrayImage(imageBytes);
        ImageIO.write(bufferedImage, "webp", new File("1.webp"));


    }

    public static byte[] base64Img2ByteArray(String base64Code) {
        byte[] imageByte = null;
        if (base64Code.startsWith("data")) {
            int index = base64Code.indexOf(',');
            base64Code = base64Code.substring(index + 1);
        }
        imageByte = Base64.getDecoder().decode(base64Code);
        return imageByte;
    }

    public static BufferedImage saveByteArrayImage(byte[] imageByte) throws IOException {
        BufferedImage image = null;
        ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
        // image = ImageIO.read(new ByteArrayInputStream(imageByte));
        image = Imaging.getBufferedImage(new ByteArrayInputStream(imageByte));

        bis.close();
        return image;
    }
}
